class ApiClient {
    constructor() {
        this.baseUrl = 'http://192.168.168.129:8080/api';
        this.defaultHeaders = {
            'Content-Type': 'application/json'
        };
    }

    async request(method, endpoint, data = null, headers = {}) {
        const url = `${this.baseUrl}${endpoint}`;
        const options = {
            method,
            headers: { ...this.defaultHeaders, ...headers },
            credentials: 'include'
        };

        if (data) {
            options.body = JSON.stringify(data);
        }

        try {
            const response = await fetch(url, options);
            
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.error || '请求失败');
            }

            // 检查响应是否有内容
            const contentLength = response.headers.get('Content-Length');
            if (contentLength === '0' || !contentLength) {
                return null;
            }

            return await response.json();
        } catch (error) {
            console.error('API请求错误:', error);
            throw error;
        }
    }

    async get(endpoint, headers = {}) {
        return this.request('GET', endpoint, null, headers);
    }

    async post(endpoint, data, headers = {}) {
        return this.request('POST', endpoint, data, headers);
    }

    async put(endpoint, data, headers = {}) {
        return this.request('PUT', endpoint, data, headers);
    }

    async delete(endpoint, headers = {}) {
        return this.request('DELETE', endpoint, null, headers);
    }

    // 检查认证状态
    async checkAuth() {
        try {
            return await this.get('/auth/check');
        } catch (error) {
            return null;
        }
    }

	// 创建订单
    async createOrder(items, deliveryAddress, contactPhone) {
        return this.post('/orders', {
            items,
            delivery_address: deliveryAddress,
            contact_phone: contactPhone
        });
    }

    // 获取订单历史
    async getOrderHistory() {
        return this.get('/orders/history');
    }

    // 取消订单
    async cancelOrder(orderId) {
        return this.put(`/orders/${orderId}/cancel`);
    }

}

const api = new ApiClient();

export default api;